package org.example.demo;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import org.jetbrains.annotations.NotNull;

public class OpenDataSourceDialogAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        if (project == null) return;

        DataSourceConfig config = DataSourceConfig.getInstance(project);
        DataSourceDialog dialog = new DataSourceDialog(project, config);
        dialog.show();

        if (dialog.getExitCode() == dialog.OK_EXIT_CODE) {
            // 保存配置
            config.dbType = dialog.getDbType();
            config.host = dialog.getHost();
            config.port = dialog.getPort();
            config.database = dialog.getDatabase();
            config.username = dialog.getUsername();
            config.password = dialog.getPassword();
            config.aiKey=dialog.getAiKeyField();

            // 测试连接
            boolean connected = testConnection(dialog.getDriverClass(), dialog.getJdbcUrl(), config.username, config.password);
            if (connected) {
                Messages.showMessageDialog(project, "✅ 连接成功，配置已保存！", "数据源配置", Messages.getInformationIcon());
            } else {
                Messages.showMessageDialog(project, "❌ 连接失败，请检查配置。", "测试连接", Messages.getErrorIcon());
            }
        }
    }

    private boolean testConnection(String driverClass, String url, String user, String password) {
        try {
            Class.forName(driverClass);
            try (java.sql.Connection conn = java.sql.DriverManager.getConnection(url, user, password)) {
                return conn.isValid(5);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}